import { Injectable, BadRequestException } from '@nestjs/common';
import { Repository, getManager, EntityManager, getConnection } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm'
import { UserEntity } from './user.entity'
import { UserExtendEntity } from './userExtend.entity'
import { RoleEntity } from '../role/role.entity'
import { async } from 'rxjs';
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
    @InjectRepository(UserExtendEntity)
    private readonly userExtendRepository: Repository<UserExtendEntity>,
    @InjectRepository(RoleEntity)
    private readonly roleRepository: Repository<RoleEntity>,
  ) { }

  async creatUser(data: { [key: string]: any }): Promise<any> {
    return await this.userRepository.save(data)
  }
  async userList(): Promise<any> {
    return await this.userRepository.find()
  }

  // 隐式commit
  async create(data: { [key: string]: any }): Promise<any> {
    const { username, age, qq, address } = data
    return getManager().
      transaction(async (entityManager: EntityManager) => {
        const user: { [key: string]: any } = await entityManager.save(
          UserEntity,
          {
            username,
            age
          }
        )
        //  throw new Error('主动抛出错误');
        return await entityManager.save(
          UserExtendEntity,
          {
            user,
            qq,
            address
          }).then(res => {
            console.log('----', res);
            return '创建成功'
          }).catch(err => {
            console.log(err);
            return '创建失败'
          })
      })
  }
  // 显示commit
  async create1(data: any) {
    const { username, age, address, qq } = data
    const connection = getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    await queryRunner.startTransaction()
    try {
      const user = await queryRunner.manager.insert<UserEntity>(UserEntity, {
        username, age
      })
      console.log('user---', user);
      // const userId = user.identifiers[0].id
      await queryRunner.manager.insert<UserExtendEntity>(UserExtendEntity, {
        user: user.generatedMaps[0],
        address,
        qq
      })
      await queryRunner.commitTransaction()
      return '创建成功'
    } catch (e) {
      await queryRunner.rollbackTransaction()
      throw new BadRequestException('创建失败')
    }
  }

  //装饰器方式
  async create2(
    data: any,
    manager: EntityManager
  ) {
    const { username, age, qq, address } = data
    const user: { [key: string]: any } = await manager.save(UserEntity, {
      username, age
    })
    await manager.save(UserExtendEntity, {
      user, qq, address
    })
    return '创建成功2'
  }


  async userAll() {
    // const manager = getManager()
    // return await manager.find(UserEntity)

    // const userRepository = getConnection().getRepository(UserEntity)
    return await this.userRepository.find({ relations: ['posts', 'role'] })
  }

  async addUserRole(data) {
    const { userld, roleld } = data
    return getManager()
    .transaction(async (entityManager: EntityManager) => {
      const role: { [key: string]: any } = await entityManager.findOne(RoleEntity,{id:roleld})
      const user: { [key: string]: any } = await entityManager.findOne(UserEntity,{id:userld})
      role.user = [user]
      user.role = [role]
      await entityManager.save(UserEntity,user)
      // throw new Error('主动抛出错误')
      await entityManager.save(RoleEntity,role)
      return '添加用户角色成功'
    })
  }

  async add(data: any) {
    const { username, age, role } = data
    console.log('username, age, role',username, age, role);
    
    return getManager()
      .transaction(async (entityManager: EntityManager) => {
       await entityManager.save(UserEntity, {
          username, age
        })
       await entityManager.save(RoleEntity, {
          role
        })
      }).then(res=>{
        console.log('res---',res);
        return '添加用户成功'
      }).catch(err=>{
        console.log('err----',err);
        return '添加用户失败'
      })
  }
}


